import json

from base.get_files_tree import get_folder_structure
from base.mysql_db import add_log
from base.ocr import recognize

# from config import FILE_PATH

if __name__ == '__main__':
    while True:
        # 从命令窗口获取用户输入的文件夹路径
        folder_path = input("请输入文件夹路径: ")
        print(folder_path.replace('\\', '/'))
        # 获取文件夹树状结构实例
        structure = get_folder_structure(folder_path.replace('\\', '/'))
        output_file_path = "folder.json"
        # 写入 JSON 数据到文件
        with open(output_file_path, 'w') as f:
            json.dump(structure, f, ensure_ascii=False, indent=4)

        print(f"JSON 数据已写入到文件: {output_file_path}")

        print("正在进行下一步操作：读取json，写入数据库")

        with open('folder.json', 'r') as file:
            folder_data = json.load(file)

        files_data = folder_data['children']
        if not files_data:
            print("----------该文件夹下无内容，结束当前文件扫描----------")
            continue
        for file_data in files_data:
            print(f"读取文件夹------{file_data['name']}")

            excel_file_data = next(
                filter(lambda d: d.get('type') == 'xls' or d.get('type') == 'xlsx', file_data['children']))
            if not excel_file_data:
                print("未获取到表格内容，跳过当前文件夹")
                continue
            print(f"获取表格内容------{excel_file_data['name']}")

            pdf_file_data = next(filter(lambda d: d.get('type') == 'folder', file_data['children']))
            if not excel_file_data:
                print("未获取到pdf列表，跳过当前文件夹")
                continue
            print(f"获取pdf列表------{pdf_file_data['name']}")

            # ocr_info = []

            for info in excel_file_data['read_info']:
                ocr_child_info = ''
                print(f"读取{info['档号']}，查找中...")
                need_ocr_info = next(filter(lambda d: d.get('name') == info['档号'] and d.get('type') == 'folder',
                                            pdf_file_data['children']))
                for ocr_image in need_ocr_info['children']:
                    print(f"解析识别内容图片：{ocr_image['name']}")
                    ocr_text = recognize(ocr_image['path'])
                    print(ocr_text)
                    ocr_child_info += ocr_text
                # ocr_info.append({
                #     'name': info['档号'],
                #     'content': ocr_child_info
                # })
                add_log({
                    'name': info['档号'],
                    'content': ocr_child_info
                })
                print('存储成功')

            # print(ocr_info)

